package com.example.concurrency.syscContainer;

import java.util.Iterator;
import java.util.Vector;

/**
 * @author 文希
 * @create 2019-05-19 19:58
 */
public class VectorExample3 {

    // java.util.ConcurrentModificationException
    private static void test1(Vector<Integer> vector) { // foreach
        for (Integer i : vector) {
            if (i.equals(3)) {
                vector.remove(i);
            }
        }
    }

    // java.util.ConcurrentModificationException
    private static void test2(Vector<Integer> vector) { // iterator
        Iterator<Integer> iterator = vector.iterator();
        while (iterator.hasNext()) {
            Integer i = iterator.next();
            if (i.equals(3)) {
                vector.remove(i);
            }
        }
    }

    // success
    private static void test3(Vector<Integer> vector) { // for

        for (int i = 0; i < vector.size(); i++) {
            if (vector.get(i).equals(3)) {
                vector.remove(i);
            }
        }
    }

    public static void main(String[] args) {
        Vector<Integer> vector = new Vector<>();
        vector.add(1);
        vector.add(2);
        vector.add(3);
//        test1(vector);
//        test2(vector);
        test3(vector);
        //vector.toString() = [1, 2]
        System.out.println("vector.toString() = " + vector.toString());
    }
}
